from Account import create_clients
from Settings import LTC_BOT_CHAT_NAME,MIN_WITHDRAW
from time import sleep
import time
import asyncio
from Console import console
import requests

async def get_CURRENCY():
    try:
        ltc_currency=float(requests.get("https://api.coinbase.com/v2/prices/LTC-USD/spot").json()['data']["amount"])
    except:
        ltc_currency=0.0
    return ltc_currency

async def for_one(client, BOT_NAME, proxy=None):
    if proxy:
        client.set_proxy(proxy)

    await client.start()

    dialog = await client.find_dialog(BOT_NAME)
    
    if not dialog:
        return 0

    await client.send_message(BOT_NAME, '/balance')

    sleep(3)
    msgs = await client.get_messages(dialog, limit=1)
    cur = 0
    sleep(3)
    try:
        for mes in msgs:
            str_a = str(mes.message)
            zz = str_a.replace('Available balance: ', '')
            qq = zz.replace(' LTC', '')
            cur = float(qq)
            
            if cur >= MIN_WITHDRAW:
                await client.send_message(BOT_NAME, '/withdraw')
                sleep(2)
                await client.send_message(BOT_NAME, client.wallet)
                sleep(1)
                console.warning("Sending {} LTC to {} wallet".format(cur, client.wallet))
                await client.send_message(BOT_NAME, str(cur))
                sleep(1)
                await client.send_message(BOT_NAME, "✔️ Confirm")

                cur = 0
            
    except Exception as e:
        console.error("Error occurred: {}".format(e))
        cur = 0
    console.info(f"@{(await client.get_me()).username}:"+"{:.6f}".format(cur)+f"LTC({cur*(await get_CURRENCY())} USD).to withdraw:"+"{:.6f} LTC".format(MIN_WITHDRAW - cur))
            
    await client.disconnect()
    return cur


async def send_total_balance(client, total,time_total):
    await client.connect()
    
    await client.notify_admins("Total LTC: {:.10f}({:.2f} USD)\n{:.3f} minutes".format(total,total*(await get_CURRENCY()),time_total))
    await client.disconnect()


async def check_balance(start_time):
    clients = create_clients()

    total = 0

    for i in range(len(clients)):


        cur = await for_one(clients[i], BOT_NAME=LTC_BOT_CHAT_NAME)
        total += cur
        sleep(1)
    time_total=(time.time() - start_time)/60
    await send_total_balance(clients[0], total,time_total)
    console.info("Total LTC: {:.10f}({:.2f} USD)\n{:.3f} minutes".format(total,total*(await get_CURRENCY()),time_total))
